# 小说

from openpyxl.worksheet.worksheet import Worksheet
from openpyxl import Workbook
from bs4.element import Tag

import sys
sys.path.append("..")
from lib.getExeclPath import getExeclPath
from lib.Spider import Spider




class ZongHeng(Spider):
    # 获取所有的书
    def getBooks(self):
        def handle(tag: Tag):
            return {
                **self.getBookName(tag),
                **self.getBookintro(tag),
                **self.getBookimg(tag)
            }
        return self.select(".bookbox", handle)

    # 返回一个只有一个键的字典
    @Spider.Decorators.field("name")
    @Spider.Decorators.text
    def getBookName(self, tag: Tag):
        return tag.select_one(".bookname")

    @Spider.Decorators.field("intro")
    @Spider.Decorators.text
    def getBookintro(self, tag: Tag):
        return tag.select_one(".bookintro")

    @Spider.Decorators.field("img")
    @Spider.Decorators.src
    def getBookimg(self, tag: Tag):
        return tag.select_one(".bookimg img")

    def appendSheet(self, sheet: Worksheet):
        for book in self.getBooks():
            sheet.append(list(book.values()))
    
    def save(self):
        book = Workbook()
        sheet = book.active
        sheet.title = "小说"
        self.appendSheet(sheet)
        book.save(getExeclPath("ZongHeng"))


if __name__ == "__main__":
    ZongHeng("http://book.zongheng.com/store/c0/c0/b0/u0/p1/v9/s1/t0/u0/i1/ALL.html").save()